<template>
  <component :is="tagName" ref="elementRef">
    <slot></slot>
  </component>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, defineProps, defineEmits, getCurrentInstance } from 'vue';
import {
  addResizeListener,
  removeResizeListener,
} from 'amtf/utils/resize-event'

defineOptions({
  name: 'vue-dom-resize-observer',
})
const instance = getCurrentInstance();
console.log(`instance 👉`, instance)
const props = defineProps({
  tagName: {
    type: String,
    required: true,
  },
  id: {
    type: [String, Number],
    default: null,
  },
});

const emit = defineEmits(['on-dom-resize-change']);
const elementRef = ref(null);

const resizeListener = (contentRect) => {
  const { left, top, width, height } = contentRect;
  emit("on-dom-resize-change", {
    key: props.id,
    left,
    top,
    width,
    height,
  });
};

onMounted(() => {
  if (elementRef.value) {
    console.log(`elementRef 👉`, elementRef)
    console.log(`elementRef.value 👉`, elementRef.value)
    addResizeListener(elementRef.value, resizeListener);
  }
});

onBeforeUnmount(() => {
  if (elementRef.value) {
    removeResizeListener(elementRef.value, resizeListener);
  }
});
</script>
